package com.engine.budget.cmd;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.hrm.User;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qbz
 * @version 1.0
 * @description: 营销项目启用及调整接口
 * @date 2024/7/29 14:43
 */
public class ActivationAdjustmentCmd extends AbstractCommonCommand<Map<String,Object>> {
    @Override
    public BizLogContext getLogContext() {
        return null;
    }
    public ActivationAdjustmentCmd(User user, Map<String,Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Object paramsObj = params.get("data");
        JSONObject paramsJson = JSONObject.parseObject(JSONObject.toJSONString(paramsObj));
        //启用：QY
        //非金额信息调整：XXTZ
        //金额调增：TZ
        //金额调减：TJ
        //金额调减校验：JY
        String instruct = paramsJson.getString("instruct");

        String itemType = paramsJson.getString("itemType");
        if (StringUtils.isEmpty(itemType)){
            return getReturnMsg("1","10002","错误的项目类别！");
        }
        String yskmBm = getBudgetAccountByYWLX(itemType);
        if (StringUtils.isEmpty(yskmBm)){
            return getReturnMsg("1","10003","科目错误！ 错误的项目类别！");
        }

        if (StringUtils.isEmpty(paramsJson.getString("projectNumber"))){
            return getReturnMsg("1","10001","项目编号错误！");
        }

        JSONObject projectNumber = selectUfYSXMDBByProjectNumber(paramsJson.getString("projectNumber"));
        if (projectNumber.isEmpty()){
            return getReturnMsg("1","10001","项目编号错误！");
        }
        JSONObject ysxmdb2 = selectUfYSXMDBByProjectNumber2(yskmBm, projectNumber.getString("id"));
        BigDecimal qzqljyzhje = ysxmdb2.getBigDecimal("qzqljyzhje");

        //全周期项目总额 调整前
        BigDecimal qzqxmzedzq = ysxmdb2.getBigDecimal("qzqxmze")== null ? BigDecimal.ZERO: ysxmdb2.getBigDecimal("qzqxmze");
        //调整后
        BigDecimal totalAmount = paramsJson.getBigDecimal("projectTotalAmount");
        //项目立项总金额-调整额
        BigDecimal subtract =totalAmount.subtract(qzqxmzedzq);

        LocalDate now = LocalDate.now();
        int year = now.getYear();
        JSONObject ysxmdb1 = selectUfYSXMDBByProjectNumber1(yskmBm, year + "");

        if (totalAmount.compareTo(qzqljyzhje.subtract(ysxmdb1.getBigDecimal("zys")).add(ysxmdb1.getBigDecimal("ndys"))) < 0){
            return getReturnMsg("1","10001","【项目立项总金额-调整后】必须大于 (项目底表全周期明细表.全周期累计已执行金额-【当前年度的年度预算表.执行数】)+【当前年度的项目年度预算】！");
        }
        JSONObject transactionBYId = getTransactionBYId(projectNumber.getString("yssx"));
        JSONObject sxdt2 = getTransactionDt2(yskmBm, transactionBYId.getString("id"));
        if (sxdt2.getBigDecimal("qzqsxze").subtract(sxdt2.getBigDecimal("qzqylxje")).add(subtract).compareTo(BigDecimal.ZERO) < 0){
            return getReturnMsg("1","10001","事项底表.全周期事项总额-[全周期已立项金额+（项目立项总金额-调整额）]必须大于0！");
        }


        if (instruct.equals("TZ") && totalAmount.compareTo(qzqxmzedzq) < 0){
            return getReturnMsg("1","10001","调增金额不得小于原有金额！");
        }
        if (instruct.equals("TJ") && totalAmount.compareTo(qzqxmzedzq) > 0){
            return getReturnMsg("1","10001","调减金额不得大于原有金额！");
        }
        if (instruct.equals("JY")){
            if (totalAmount.compareTo(qzqxmzedzq) > 0){
                return getReturnMsg("1","10001","调减金额不得大于原有金额！");
            } else {
                return getReturnMsg("0","10000","校验通过");
            }

        }
        //全周期调整额
        BigDecimal qzqdzed = subtract.add(ysxmdb2.getBigDecimal("qzqdzed"));

        //全周期已立项金额
        BigDecimal qzqylxje = sxdt2.getBigDecimal("qzqylxje").add(subtract);
        BigDecimal qzqsxze = sxdt2.getBigDecimal("qzqsxze");
        //全周期剩余可立项金额
        BigDecimal bigDecimal = qzqsxze.subtract(qzqylxje);
        String id = sxdt2.getString("id");
        updateYsxmdb2(ysxmdb2,qzqdzed,qzqylxje,id,paramsJson.getString("projectNumber"),totalAmount,bigDecimal);
        return getReturnMsg("0","10000",null);
    }

    //查询事项表
    public JSONObject getTransactionBYId(String num){
        String sql = "select * from uf_yssxdb where sxbm = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, num);
        JSONObject res = new JSONObject();
        while (rs.next()){
            //事项编码
            res.put("id",rs.getString("id"));
            res.put("sxbm",rs.getString("sxbm"));
            //事项名称
            res.put("sxmc",rs.getString("sxmc"));
            res.put("zdbz",rs.getString("zdbz"));
        }
        return res;
    }
    /**
     *  查询事项明细2表 根据预算科目
     */

    public JSONObject getTransactionDt2(String yskm,String mainid){
        ArrayList<String> strings = new ArrayList<>();
        strings.add(yskm);
        strings.add(mainid);
        String sql = "select * from uf_yssxdb_dt2 where yskm = ? and mainid = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, strings);
        JSONObject res = new JSONObject();
        while (rs.next()){
            //全周期事项总额
            res.put("qzqsxze",StringUtils.isEmpty(rs.getString("qzqsxze")) ? "0": rs.getString("qzqsxze"));
            //全周期调整额度
            res.put("qzqdzed",StringUtils.isEmpty(rs.getString("qzqdzed")) ? "0": rs.getString("qzqdzed"));
            res.put("qzqylxje",StringUtils.isEmpty(rs.getString("qzqylxje")) ? "0": rs.getString("qzqylxje"));
        }
        return res;
    }

    /**
     * 查询项目底表明细1表
     * @return
     */
    public JSONObject selectUfYSXMDBByProjectNumber1(String yskm,String ysnd){

        ArrayList<String> strings = new ArrayList<>();
        strings.add(yskm);
        strings.add(ysnd);
        String sql = "select * from uf_ysxmdb_dt1 where yskm = ? and ysnd = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, strings);
        JSONObject jsonObject = new JSONObject();
        while (rs.next()){
            jsonObject.put("dwjzdgz",rs.getString("dwjzdgz"));
            jsonObject.put("ysnd",rs.getString("ysnd"));
            jsonObject.put("yskm",rs.getString("yskm"));
            jsonObject.put("ndqcys",rs.getString("ndqcys"));
            jsonObject.put("nddzysnz",rs.getString("ndqcysnz"));
            jsonObject.put("nddzyslx",rs.getString("ndqcyslx"));
            jsonObject.put("ndys",rs.getString("ndys"));
            jsonObject.put("zxs",rs.getString("zxs"));
            jsonObject.put("zys",rs.getString("zys"));
            jsonObject.put("fsze",rs.getString("fsze"));
            jsonObject.put("ysye",rs.getString("ysye"));

        }
        return jsonObject;
    }
    public Map<String,Object> getReturnMsg(String status,String errorCode,String errorMessage){
        HashMap<String, Object> res = new HashMap<>();
        HashMap<String, Object> result = new HashMap<>();
        result.put("status",status);
        result.put("errorCode",errorCode);
        result.put("errorMessage",errorMessage);
        result.put("data",new ArrayList<Object>());
        res.put("result",result);
        return res;
    }


    /**
     * 根据业务类型编码查询
     * @param ywxlBm
     * @return
     */
    public String getBudgetAccountByYWLX(String ywxlBm){
        String sql = "select * from uf_jccs_yskmysxmywlx where ysxmywlxbm = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, ywxlBm);
        String yskmBm = null;
        while (rs.next()){
            yskmBm = rs.getString("yskmbm");
        }
        return yskmBm;
    }
    /**
     * 查询项目底表
     * @param projectNumber
     * @return
     */
    public JSONObject selectUfYSXMDBByProjectNumber(String projectNumber){
        String sql = "select * from uf_ysxmdb where xmbm = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, projectNumber);
        JSONObject jsonObject = new JSONObject();
        while (rs.next()){
            jsonObject.put("zxdw",rs.getString("zxdw"));
            jsonObject.put("id",rs.getString("id"));
            jsonObject.put("xmbm",rs.getString("xmbm"));
            jsonObject.put("xmmc",rs.getString("xmmc"));
            jsonObject.put("ywlx",rs.getString("ywlx"));
            jsonObject.put("ywxl",rs.getString("ywxl"));
            jsonObject.put("zz",rs.getString("zz"));
            jsonObject.put("hdnf",rs.getString("hdnf"));
            jsonObject.put("sfgb",rs.getString("sfgb"));
            jsonObject.put("qbmc",rs.getString("qbmc"));
            jsonObject.put("qbzje",rs.getString("qbzje"));
            jsonObject.put("xmzbrgh",rs.getString("xmzbrgh"));
            jsonObject.put("xmzbrmc",rs.getString("xmzbrmc"));
            jsonObject.put("xmqdsj",rs.getString("xmqdsj"));
            jsonObject.put("xmjssj",rs.getString("xmjssj"));
            jsonObject.put("szjyjhzd",rs.getString("szjyjhzd"));
            jsonObject.put("ywxmbm",rs.getString("ywxmbm"));
            jsonObject.put("ywxmmc",rs.getString("ywxmmc"));
            jsonObject.put("ywxmid",rs.getString("ywxmid"));
            jsonObject.put("xmmblx",rs.getString("xmmblx"));
            jsonObject.put("szywcp",rs.getString("szywcp"));
            jsonObject.put("modedatamodifier",rs.getString("modedatamodifier"));
            jsonObject.put("modedatamodifydatetime",rs.getString("modedatamodifydatetime"));
            jsonObject.put("yssx",rs.getString("yssx"));

        }
        return jsonObject;
    }
    /**
     * 查询项目底表明细2表
     * @return
     */
    public JSONObject selectUfYSXMDBByProjectNumber2(String yskm,String mainid){
        ArrayList<String> strings = new ArrayList<>();
        strings.add(yskm);
        strings.add(mainid);
        String sql = "select * from uf_ysxmdb_dt2 where yskm = ? and mainid = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, strings);
        JSONObject jsonObject = new JSONObject();
        while (rs.next()){
            jsonObject.put("yskm",rs.getString("yskm"));
            jsonObject.put("qzqqcze",rs.getString("qzqqcze"));
            jsonObject.put("qzqdzed",rs.getString("qzqdzed"));
            jsonObject.put("zxs",rs.getString("zxs"));
            jsonObject.put("zys",rs.getString("zys"));
            jsonObject.put("qzqljyzhje",rs.getString("qzqljyzhje"));
            jsonObject.put("qzqsykzhje",rs.getString("qzqsykzhje"));
            jsonObject.put("qzqxmze",rs.getString("qzqxmze"));
            jsonObject.put("id",rs.getString("id"));
        }
        return jsonObject;
    }


    /**
     * 跟新预算项目明细2表
     * @return
     */
    public void updateYsxmdb2(JSONObject json1, BigDecimal money,BigDecimal money2,String id2,String proNum,BigDecimal money3,BigDecimal money4){
        String id = json1.getString("id");
        BigDecimal qzqqcze = json1.getBigDecimal("qzqqcze");
        //全周期项目总额
        BigDecimal qzqxmze = qzqqcze.add(money);

        BigDecimal zhs = json1.getBigDecimal("zxs");
        BigDecimal zys = json1.getBigDecimal("zys");

        BigDecimal qzqljyzxje = zhs.add(zys);

        BigDecimal qzqsykzxje = qzqxmze.subtract(qzqljyzxje);


        ArrayList<Object> strings = new ArrayList<>();
        strings.add(money);
        strings.add(qzqxmze);
        strings.add(qzqljyzxje);
        strings.add(qzqsykzxje);
        strings.add(id);
        String sql = "update uf_ysxmdb_dt2 set qzqdzed = ?,qzqxmze=?,qzqljyzhje=?,qzqsykzhje=? where id = ?";
        RecordSet rs = new RecordSet();
        rs.executeUpdate(sql, strings);


        ArrayList<Object> strings1 = new ArrayList<>();
        strings1.add(money2);
        strings1.add(money4);
        strings1.add(id2);
        String sql1 = "update uf_yssxdb_dt2 set qzqylxje = ?,qzqsyklxje=? where id = ?";
        RecordSet rs1 = new RecordSet();
        rs1.executeUpdate(sql1, strings1);

        //更新流程表
        Integer workflowid = Integer.valueOf(Prop.getPropValue("businessbudgetpz", "marketProjectWorkFlowId"));
        String tableName = getTableNameBYWorkflowid(workflowid);

        ArrayList<Object> strings3 = new ArrayList<>();
        strings3.add(money3);
        strings3.add(proNum);
        String sql5 = "update "+tableName+" set xmlxzjewy = ? where xmbh = ?";
        RecordSet rs3 = new RecordSet();
        rs3.executeUpdate(sql5, strings3);
    }
    /**
     * 根据workflowid查询表名称
     * @param workflowid
     */
    public String getTableNameBYWorkflowid(Integer workflowid){

        String sql = "select t.id workflowid, t2.TABLENAME  from workflow_base t " +
                "left join workflow_bill t2 on t.FORMID = t2.id " +
                "WHERE t.id = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, workflowid);
        String tableName = null;
        while (rs.next()){
            tableName = rs.getString("TABLENAME");
        }
        return tableName;

    }
}
